﻿using LotteryCrawler.Core;
using SuperLottery.AdminPortal.Models;
using SuperLottery.Datas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Web.Http;

namespace SuperLottery.AdminPortal.Controllers
{
	public class CrawlerController : ApiController
	{
		public DrawModel Get()
		{
			return this.Get(null);
		}

		public DrawModel Get(string id)
		{
			if (String.IsNullOrEmpty(id))
			{
				id = this.GetNextIssueNumber("福彩", "双色球");
			}

			XCrawler xCrawler = new XCrawler();
			return xCrawler.Crawl(id);
		}

		public DrawModel GetQiLeCai()
		{
			return this.GetQiLeCai(null);
		}

		public DrawModel GetQiLeCai(string id)
		{
			if (String.IsNullOrEmpty(id))
			{
				id = this.GetNextIssueNumber("福彩", "七乐彩");
			}

			XCrawler xCrawler = new XCrawler();
			return xCrawler.CrawlQiLeCai(id);
		}

		public DrawResult GetDrawResult(string issuerGame, string issueNumber)
		{
			Crawler crawler = new Crawler();
			switch (issuerGame)
			{
 				case "福彩-双色球":
					return crawler.CrawlShuangSeQiu(issueNumber);
				case "福彩-七乐彩":
					return crawler.CrawlQiLeCai(issueNumber);
				case "体彩-大乐透":
					return crawler.CrawlDaLeTou(issueNumber);
				default:
					return null;
			}
		}

		private String GetNextIssueNumber(string issuer, string game)
		{
			var latest = LotteryDrawDbService.Instance.GetLatestLotteryDraw(issuer, game);
			if (latest != null)
			{
				return (Int32.Parse(latest.IssueNumber) + 1).ToString();
			}
			return "";
		}
	}
}
